package cn.edu.zzu.demo03ThreadSecurity;

/**
 * 取钱案例
 */
public class TestUnSecurity02 {
    public static void main(String[] args) {
        Account account = new Account("结婚基金", 1000);
        new WithDrawing(account , 100 ,"老婆").start();
        new WithDrawing(account , 50 ,"老公").start();
    }
}

class Account {
    String accountName;
    Integer accountMoney;

    public Account(String accountName, Integer accountMoney) {
        this.accountName = accountName;
        this.accountMoney = accountMoney;
    }
}


class WithDrawing extends Thread {

    private Account account; //取款的账户信息

    private Integer withDrawNum; //取款数

    private Integer nowMoney = 0; //已取得钱数

    public WithDrawing(Account account, Integer withDrawNum, String threadName) {
        super(threadName);
        this.account = account;
        this.withDrawNum = withDrawNum;
    }

    @Override
    public void run() {
        //同步代码块，将共享操作的对象进行锁定，变化的量进行锁定  synchronized(Object){}
      synchronized (account){

          if (account.accountMoney < withDrawNum) {
              System.out.println("账户：" + account.accountName + "余额不足！" + account.accountMoney);
              return;
          }

          account.accountMoney = account.accountMoney - withDrawNum;
          nowMoney = nowMoney + withDrawNum;

          System.out.println(Thread.currentThread().getName()+"在账户："+account.accountName+"取款了："+withDrawNum);
          System.out.println(Thread.currentThread().getName()+"手里有："+nowMoney);
          System.out.println("账户："+account.accountName+"余额："+account.accountMoney);
      }
    }
}